package com.bbcare.followup.plat.controller;

import com.alibaba.fastjson.JSON;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PtUserInfoCollect;
import com.bbcare.followup.plat.service.impl.PatientService;
import com.bbcare.followup.plat.service.impl.PtUserInfoCollectService;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Title		PtUserInfoCollectController.java
 * @Package		com.bbcare.followup.plat.controller
 * @Description	患者建档信息总表控制器
 * @Author		<a href="mailto:jiangqian_java@163.com">jiang</a>
 * @Date		2023/9/11
 * @Version		V1.0 
 * @Copyright	(c) Shanghai BBcare Medical Equipment Co.,Ltd.
 */
@RestController
@RequestMapping("/ptUserInfoCollect")
public class PtUserInfoCollectController {

    private static Logger logger = Logger.getLogger(PtUserInfoCollectController.class);

    @Resource
    private PtUserInfoCollectService patientCollectService;

    @Resource
    private PatientService patientService;

    @Resource
    private IPatientDAO patientDAO;

    /**
     * 同步病人数据，从pt_user_info -> pt_user_info_collect
     * @return
     */
    @RequestMapping("/syncPatientInfo")
    public ResultModel syncPatientInfo(@RequestBody String arg, HttpServletRequest request) throws Exception {
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");

        List<Patient> patients = patientDAO.select(paramMap);
        logger.info("================================================================ patients.size " + patients.size());



        //查询汇总表的数据
        List<PtUserInfoCollect> userInfoCollects = patientCollectService.getDataByCondition(new PtUserInfoCollect());
        logger.info("================================================================ userInfoCollects.size " + userInfoCollects.size());

        if(patients != null && patients.size() > 0){
            for (Patient patient : patients) {
                String patientId = patient.getId();
                String userName = patient.getUserName();
                String gender = patient.getGender();
                String birthday = patient.getBirthday();
                String expectedDay = patient.getExpectedDay();
                int pregnancyDay = patient.getPregnancyDay();
                String phoneNo = patient.getPhoneNo();
                //根据patientId先查询是否存在
                List<PtUserInfoCollect> collect = userInfoCollects.stream().filter(item -> item.getPatientId().equals(patientId)).collect(Collectors.toList());

                if(null == collect || collect.size() == 0){
                    //patientId不存在，再用以上条件进行数据筛选合并选项,条件缺一不可。
                    collect = userInfoCollects.stream().filter(item -> {
                                try {
                                    return item.getUserName().equals(userName) && item.getGender().equals(gender)
                                            && item.getBirthday().equals(birthday) && DateUtil.getDate_8(item.getExpectedDay()).equals(expectedDay)
                                            && item.getPregnancyDay().equals(pregnancyDay) && item.getPhoneNo().equals(phoneNo);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                return false;
                            }
                    ).collect(Collectors.toList());
                    if(collect.size() > 0){
                        PtUserInfoCollect mainUserInfo = collect.stream().filter(item -> item.getId().equals(item.getMainPatientId())).collect(Collectors.toList()).get(0);
                        //复制数据
                        patient.setId(null);
                        PtUserInfoCollect ptUserInfo = JSON.parseObject(JSON.toJSONString(patient), PtUserInfoCollect.class);
                        ptUserInfo.setPatientId(patientId);
                        ptUserInfo.setMainPatientId(mainUserInfo.getId());
                        patientCollectService.insert(ptUserInfo);
                        userInfoCollects.add(ptUserInfo);
                    }else{
                        //首次入表
                        patient.setId(null);
                        PtUserInfoCollect ptUserInfo = JSON.parseObject(JSON.toJSONString(patient), PtUserInfoCollect.class);
                        ptUserInfo.setPatientId(patientId);
                        patientCollectService.insert(ptUserInfo);
                        ptUserInfo.setMainPatientId(ptUserInfo.getId());
                        patientCollectService.update(ptUserInfo);
                        userInfoCollects.add(ptUserInfo);
                    }
                }
            }
        }
        return new ResultModel("over");
    }


    /**
     * 新增
     * @author jiangq
     * @date 2023/09/11
     **/
    @RequestMapping("/insert")
    public ResultModel insert(PtUserInfoCollect ptUserInfoCollect){
        return new ResultModel(patientCollectService.insert(ptUserInfoCollect));
    }

    /**
     * 刪除
     * @author jiangq
     * @date 2023/09/11
     **/
    @RequestMapping("/delete")
    public ResultModel delete(int id){
        return new ResultModel(patientCollectService.delete(id));
    }

    /**
     * 更新
     * @author jiangq
     * @date 2023/09/11
     **/
    @RequestMapping("/update")
    public ResultModel update(PtUserInfoCollect ptUserInfoCollect){
        return new ResultModel(patientCollectService.update(ptUserInfoCollect));
    }

    /**
     * 查询 根据主键 id 查询
     * @author jiangq
     * @date 2023/09/11
     **/
    @RequestMapping("/load")
    public ResultModel load(int id){
        return new  ResultModel(patientCollectService.load(id));
    }

    /**
     * 查询 分页查询
     * @author jiangq
     * @date 2023/09/11
     **/
    @RequestMapping("/pageList")
    public ResultModel pageList(@RequestParam(required = false, defaultValue = "0") int offset,
                                        @RequestParam(required = false, defaultValue = "10") int pagesize) {
        return new ResultModel(patientCollectService.pageList(offset, pagesize));
    }

}
